package site.codeyin.javautils.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.stereotype.Service;
import site.codeyin.javautils.service.LockService;

import javax.annotation.Resource;
import java.util.concurrent.TimeUnit;

/**
 * @author <a href="https://github.com/liangcheng2221">yinjie</a>
 * @date 2024-11-17 0:20
 */
@Service("redssion")
@Slf4j
public class ReddsionDistributedLockService implements LockService {

    @Resource
    private RedissonClient redissonClient;

    /**
     * 获取锁
     *
     * @param key
     * @param expireTime
     * @param waitTime
     * @return
     * @throws Throwable
     */
    @Override
    public RLock lock(String key, long expireTime, long waitTime) throws Throwable {
        RLock lock = redissonClient.getLock(key);
        boolean tryLock = lock.tryLock(waitTime, expireTime, TimeUnit.MILLISECONDS);
        return tryLock ? lock : null;
    }

    /**
     * 获取锁
     *
     * @param lock
     */
    @Override
    public Boolean unlock(RLock lock) {
        if (lock == null) {
            log.error("lock is null");
            return false;
        }
        if (lock.isLocked() && lock.isHeldByCurrentThread()) {
            lock.unlock();
            log.error("锁释放成功");
            return true;
        } else {
            log.error("unlock failed, lock is not locked or not held by current thread");
            return false;
        }
    }

}
